package com.itheima.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.dao.base.IAreaRepository;
import com.itheima.bos.dao.base.IFixedAreaRepository;
import com.itheima.bos.dao.take_delivery.IOrderRepository;
import com.itheima.bos.dao.take_delivery.IWorkBillRepository;
import com.itheima.bos.domain.base.Area;
import com.itheima.bos.domain.base.Courier;
import com.itheima.bos.domain.base.FixedArea;
import com.itheima.bos.domain.base.SubArea;
import com.itheima.bos.domain.constant.Constant;
import com.itheima.bos.domain.take_delivery.Order;
import com.itheima.bos.domain.take_delivery.WorkBill;
import com.itheima.bos.service.take_delivery.IOrderService;

@Service
@Transactional
public class OrderServiceImpl implements IOrderService {

	@Autowired
	private IFixedAreaRepository fixedAreaRepository;

	@Autowired
	private IOrderRepository orderRepository;

	@Autowired
	private IAreaRepository areaRepository;

	@Autowired
	private IWorkBillRepository workBillRepository;

	// 注入消息队列模板
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	// 分单
	@Override
	public void saveOrder(Order order) {
		// 设置订单号
		order.setOrderNum(UUID.randomUUID().toString());
		// 设置订单时间
		order.setOrderTime(new Date());
		// 设置订单状态为代取件
		order.setStatus("1");
		// 寄件人
		Area sendArea = order.getSendArea();
		Area persistArea = areaRepository.findByProvinceAndCityAndDistrict(
				sendArea.getProvince(), sendArea.getCity(),
				sendArea.getDistrict());
		// 收件人
		Area recArea = order.getRecArea();
		Area persistRecArea = areaRepository
				.findByProvinceAndCityAndDistrict(recArea.getProvince(),
						recArea.getCity(), recArea.getDistrict());
		order.setSendArea(persistArea);
		order.setRecArea(persistRecArea);

		// 自动分单(完全路径匹配)
		String fixedAreaId = WebClient
				.create(Constant.CRM_MANAGEMENT_URL
						+ "/services/customerService/customer/findfixedAreaIdByAddress?address="
						+ order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);
		if (fixedAreaId != null) {
			// 根据定区id返回一个定区对象
			FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
			Courier courier = fixedArea.getCouriers().iterator().next();
			if (courier != null) {
				// 分单成功
				System.out.println("自动分单成功");
				// 将快递员于订单关联
				/*
				 * order.setCourier(courier); orderRepository.save(order);
				 */
				saveOrder(order, courier);
				// 生成工单，发送短信
				generateWorkBill(order);
				return;
			}
		}
		// 自动分单通过区域查找所有的分区，根据关键字或是辅助关键字查找
		for (SubArea subArea : persistArea.getSubareas()) {
			// 根据关键字查找
			if (order.getSendAddress().contains(subArea.getKeyWords())) {
				// 找打分区 ,找到定区、找到快递员
				Iterator<Courier> iterator = subArea.getFixedArea()
						.getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						// 自动分单成功
						System.out.println("自动分单成功....");
						saveOrder(order, courier);

						// 生成工单 发送短信
						generateWorkBill(order);

						return;
					}
				}
			}
		}
		// 自动分单通过区域查找所有的分区，根据关键字或是辅助关键字查找
		for (SubArea subArea : persistArea.getSubareas()) {
			// 当前客户的下单地址 是否包含分区 辅助关键字
			if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
				// 找打分区 ,找到定区、找到快递员
				Iterator<Courier> iterator = subArea.getFixedArea()
						.getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						// 自动分单成功
						System.out.println("自动分单成功....");
						saveOrder(order, courier);

						// 生成工单 发送短信
						generateWorkBill(order);

						return;
					}
				}

			}
		}

		// 进入人工分单
		order.setOrderType("2");
		orderRepository.save(order);
	}

	// 生成工单，发送短信
	public void generateWorkBill(final Order order) {
		// 生成工单
		WorkBill workBill = new WorkBill();
		workBill.setType("新");
		workBill.setPickstate("新单");
		workBill.setBuildtime(new Date());
		workBill.setRemark(order.getRemark());
		workBill.setSmsNumber(RandomStringUtils.randomNumeric(4));
		workBill.setCourier(order.getCourier());
		workBill.setOrder(order);
		workBillRepository.save(workBill);

		// 发送短信
		// 编写短信内容
		final String sendSms = "短信序号：" + workBill.getSmsNumber() + "，取件地址："
				+ order.getSendAddress() + ",联系人：" + order.getSendName()
				+ ",取件电话：" + order.getSendMobile() + "服务电话为：400212455";
		jmsTemplate.send(new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier()
						.getTelephone());
				mapMessage.setString("sendSms", sendSms);
				return mapMessage;
			}
		});

		// 修改工单状态
		workBill.setPickstate("已通知");
	}

	// 自动分段保存
	public void saveOrder(Order order, Courier courier) {
		order.setCourier(courier);
		order.setOrderType("1");
		orderRepository.save(order);
	}
	
	//根据订单号查询订单
	@Override
	public Order findByOrderNum(String orderNum) {
		return orderRepository.findByOrderNum(orderNum);
	}
}
